import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Steps, Button, message, Progress, Modal } from "antd";
import styles from './card.css';
// import iconfont from '../../assets/fonts/iconfont.css'
import axios from 'axios'

import StepPage from '../../components/CardProcess/StepPage/StepPage';
import Agreements from '../../components/CardProcess/Agreements/Agreements';
import EditInfo from '../../components/CardProcess/EditInfo/EditInfo';
import Password from '../../components/CardProcess/password/password';
import Sign from '../../components/CardProcess/sign/sign';
import Tables from '../../components/CardProcess/tables/tables';
import Finished from '../../components/CardProcess/Finished/Finished'



const Step = Steps.Step;

class CardProcess extends Component {
    constructor(props) {
        super(props);
        this.state = {
            current: 0,
            status: null,
            num: 0, // 调用next()次数
            // Threestate: false,
            disabled: false, // 按钮禁用
        };
    }

    next() {
        if (this.state.current === 0 && this.props.data.Onestate || this.state.current === 1 || this.state.current === 2 && this.props.data.Twostate || this.state.current === 3 && this.props.data.Fourstate) { // 1 -> 2
            const current = this.state.current + 1;
            this.setState({
                current: current,
                num: 0,
            });
        } else if (this.state.current === 4 && this.props.data.Threestate) {
            console.log('下一步触发取卡')
            // 页面加载完成   取卡动作
            this.props.dispatch({
                type: 'cardProcess/spinState',
                payload: {
                    spinState: true
                }
            });
            this.setState({ disabled: true });
            this.action()
        } else if (this.state.current === 2 && this.state.num !== 1 || this.state.current === 3 && this.state.num !== 1 || this.state.current === 4 && this.state.num !== 1) { // 2 自处理
            this.formRef.handleSubmit();
            this.setState({ num: this.state.num + 1 });
            setTimeout(() => {
                this.next()
            }, 1);
        } else {
            message.warning('请完善信息后再进行下一步操作！');
            this.setState({ num: 0 });
        }

    }

    // openNotificationWithIcon = (type,errorCode,errorMsg) => { // 通知提醒
    //     notification[type]({
    //         message: '错误代码:' + errorCode,
    //         description: errorMsg
    //     })
    // }

    prev() {
        const current = this.state.current - 1;
        this.setState({
            current: current,
            nextFlag: false,
            num: 0,
        });
    }

    componentWillMount() {
        clearTimeout(global.timer2);
        this.props.dispatch({
            type: 'clock/change',
            payload: {
                visible: false
            }
        })
    }

    onChildChanged = (checked) => {
        this.setState({
            nextFlag: checked
        });
    }

    handleSubmitMsg = () => {
        const userInfo = this.props.data;
        console.log('提交', userInfo)
        if (userInfo.postDataResult === '0') {
            // 完成操作   发卡
            this.props.dispatch({
                type: 'cardProcess/sendCard',
            })
            this.props.dispatch(routerRedux.push('/'))
        } else {
            console.log('返回首页')
            this.props.dispatch(routerRedux.push('/'))
        }
    }

    error(errorCode, msg) { // 错误提示确认
        const _this = this;
        Modal.error({
            title: '错误代码：' + errorCode,
            content: '错误信息：' + msg,
            okText: '确认',
            onOk: function () {
                _this.setState({ current: _this.state.current + 1 }); // 跳转下一页
            }
        });
    }


    action = () => {
        const _this = this;
        console.log('进入----------->')
        const Get_url = 'http://127.0.0.1:8181/crd_gd.pof?timeout=20&action=1&unit=2';  // 取卡
        const Read_Url = 'http://127.0.0.1:8181/crd_gd.pof?timeout=20&dqfs=0&devtype=8'; // 读卡
        const Post_url = 'http://10.1.45.100:9010/nofsrv/services'; // 提交数据
        let fdata = null;
        let sdata = null;
        let tdata = null;
        axios.get(Get_url) // 取卡
            .then(function (response) {
                fdata = response.data;
                console.log(fdata)
                fdata = fdata.replace("=", ":");
                fdata = eval('(' + fdata + ')');
                console.log('Return-取卡');
                console.log(fdata);
                if (fdata.result === '0') { // 取卡成功
                    axios.get(Read_Url) // 读卡
                        .then(function (response) {
                            sdata = response.data;
                            console.log(sdata)
                            sdata = sdata.replace("=", ":");
                            sdata = eval('(' + sdata + ')');
                            console.log('Return-读卡');
                            console.log(sdata);
                            // 数据整合
                            let _Data = {
                                "chandt": "20180401",
                                "chanflow": "2018000000001",
                                "chanid": "13",
                                "orgcode": "8020400",
                                "srvname": "100002",
                                "teller": "000207",
                                "token": "asdfsdfsdf"
                            }
                            console.log(_Data)
                            var Arr = ['phoneNumber', 'code', 'postcode', 'position', 'location', 'password', 'YXT', 'ATM', 'mobileBank', 'webBank'];
                            console.log(_this.props)
                            const userInfo = _this.props.data;
                            console.log(userInfo)
                            const IdInfo = _this.props.idMsg.data;
                            console.log(IdInfo)
                            // const ArrLen = Arr.length;
                            let dataJson = {};
                            for (var i = 0, len = Arr.length; i < len; i++) { // 添加 用户相关数据
                                var _i = i;
                                var key = Arr[_i];
                                dataJson[key] = userInfo[key];
                            }
                            for (const key in IdInfo) { // 添加 身份信息
                                if (IdInfo.hasOwnProperty(key)) {
                                    dataJson[key] = IdInfo[key];
                                }
                            }
                            console.log('读卡数据', sdata)
                            dataJson.cardNo = sdata.value; // 添加 卡信息
                            console.log('整合数据', dataJson)
                            // dataJson.srvname = '100002';
                            // dataJson.orgcode = '100000';
                            _Data['data'] = dataJson;
                            console.log('完全数据', _Data)
                            if (sdata.result === '0') { // 读卡成功
                                axios.post(Post_url, JSON.stringify(_Data), {
                                    headers: {
                                        "Content-Type": "application/json;charset=utf-8"
                                    }
                                })
                                    .then(function (response) {
                                        tdata = response.data;
                                        if (tdata.result === '0') {
                                            _this.props.dispatch({
                                                type: 'cardProcess/postResult',
                                                payload: tdata.result
                                            })
                                            _this.setState({ current: _this.state.current + 1 });
                                        } else {
                                            _this.error(tdata.result, tdata.msg)
                                        }
                                    })
                                    .catch(function (error) {
                                        if (error.response) {
                                            // The request was made and the server responded with a status code
                                            // that falls out of the range of 2xx
                                            console.log(error.response.data);
                                            console.log(error.response.status);
                                            console.log(error.response.headers);
                                        } else if (error.request) {
                                            // The request was made but no response was received
                                            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                                            // http.ClientRequest in node.js
                                            console.log(error.request);
                                        } else {
                                            // Something happened in setting up the request that triggered an Error
                                            console.log('Error', error.message);
                                        }
                                        console.log(error.config);
                                    });
                            } else {
                                _this.error(sdata.result, sdata.msg)
                            }
                        })
                } else {
                    _this.error(fdata.result, fdata.msg)
                }
            })
            .catch(function (error) {
                _this.error('null', '设备出现问题！请联系工作人员处理！')
            })
    }

    render() {
        const { current } = this.state;
        const { data } = this.props;
        const steps = [{
            title: '卡种选择',
            content: <StepPage fristCheck={data.fristCheck} />,
        }, {
            title: '阅读协议',
            content: <Agreements />,
        }, {
            title: '信息确认',
            content: <EditInfo wrappedComponentRef={(inst) => this.formRef = inst} par_infoData={data} />,
        }, {
            title: '综合业务签约',
            content: <Sign wrappedComponentRef={(inst) => this.formRef = inst} par_checks={data} />,
        }, {
            title: '交易密码设置',
            content: <Password wrappedComponentRef={(inst) => this.formRef = inst} par_pwd={data} height={global.MainH - 160} />,
        }, {
            title: '完成',
            content: <Finished />,
        }];
        const percent = (this.state.current + 1) * (100 / 6);
        return (
            <div className={styles.container} style={{ height: global.MainH }}>
                <Steps className={styles.steps} current={current}>
                    {steps.map(item => <Step key={item.title} title={item.title} />)}
                </Steps>
                {/* 进度条 */}
                <Progress percent={percent} status="active" showInfo={false} />
                <div className={styles.content} style={{ height: global.MainH - 160 }}>{steps[this.state.current].content}</div>
                <div className={styles.action} style={{ textAlign: 'center' }}>
                    {
                        this.state.current > 0 && this.state.current !== steps.length - 1
                        &&
                        <Button style={{ marginRight: 8 }} disabled={this.state.disabled} onClick={() => this.prev()}>返回/Return</Button>
                    }
                    {
                        this.state.current < steps.length - 1
                        &&
                        <Button type="primary" disabled={this.state.disabled} onClick={() => this.next()}>下一步/Enter</Button>
                    }
                    {
                        this.state.current === steps.length - 1
                        &&
                        <Button type="primary" onClick={this.handleSubmitMsg}>完成/Finished</Button>
                    }

                </div>
            </div>
        );
    }
}
function mapStateToProps(state) {
    console.log(state)
    const data = state.cardProcess;
    const idMsg = state.getCard;
    return { data, idMsg };
}
export default connect(mapStateToProps)(CardProcess);